<template>
  <div id="app">
  <el-form :model="ruleForm" :rules="rule" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="活动名称" prop="value">
      <treeselect v-bind="$attrs"
                v-on="$listeners" :disable-branch-nodes="true" v-model="ruleForm.value" @input="changeValue" @select="selectValue" :multiple="false" :options="options"  :normalizer="normalizer"/>
    </el-form-item>
    
  </el-form>
  <!-- <el-button @click="doSubmit('ruleForm')">
    确定
  </el-button> -->
  </div>
</template>

<script>
  // import the component
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import { getTreeData } from '@/api/market/product.js'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  export default {
    // register the component
    components: { Treeselect },
    data () {
      return {
        // define the default value
        ruleForm:{ value: null},
        // define options
        options: [],
        rule: {
            value: [
              {
                required: true,
                message: "请选择分类",
                trigger: 'input'  
              }
            ]
      }
			}
      
    },
    methods: {
      doSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log('submit!!');
            return true
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      changeValue() {
        this.$nextTick(()=>{
          this.$refs["ruleForm"].validateField("value");
        })
        },
      normalizer (node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      //递归删除空数组
      exec(array) {
        array.forEach(item => {
              if (item.children.length === 0) {
                  delete item.children
            } else {
                  this.exec(item.children)
            }
        })
      },
      selectValue(val){
        this.$emit('getValue',val)
      },
      getTreeData (id) {
        getTreeData({ id: id }).then((res) => {
          if (res.data.code === '200') {
            // for (let index = 0; index < res.data.result.length; index++) {


            // }
            this.options = res.data.result
            this.exec(this.options)
            console.log(this.options)
          }
        })
      }
    },
    mounted: function () {
      this.getTreeData(0)
    }
  }
</script>
